<style lang="less">
@import "../../styles/common.less";
@import "staff.less";
</style>

<template>
  <div class="margin-top-10">
    <!-- <Row type="flex" justify="space-between"> -->
    <div class="margin-top-10">
      <Table :columns="guestColumn" :data="guestData" :loading="tableLoading"></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="totalGuest"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="getStranger"
        show-total
      >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalGuest}}条</Page>
    </Row>

    <AddGuestModal ref="addGuestModal" @updated="updated"/>
    <AddStaffModal ref="addStaffModal" @updated="updated"/>
    <AddVIPModal ref="addVIPModal" @updated="updated"/>
    <MergeToModal ref="mergeToModal" @updated="updated"/>
  </div>
</template>

<script>
import {
  addOrUpdateGuest,
  getStrangerData,
  deleteUser,
  getAvatar,
  getFeature,
  regFeature,
  delFeature,
  uploadGuestData,
  recovery
} from "../../controllers/user";

import Constant from "../../libs/constants";
import _ from "lodash";
import pic from "../../images/upload.png";
import fakeAvatar from "../../images/default_avatar.png";
import DateUtils from "../../../node_modules/iview/src/utils/date";
import row from "../../../node_modules/iview/src/components/grid/row";
import col from "../../../node_modules/iview/src/components/grid/col";
import ImageUtils from "@/libs/image.js";

import iconDelete from "../../images/delete.png";
import iconEdit from "../../images/edit.png";
import iconFeature from "../../images/feature.png";

import excelFile from "../../assets/guestExcel.xlsx";

import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";

import AddGuestModal from "../record/components/AddGuestModal";
import AddStaffModal from "../record/components/AddStaffModal";
import AddVIPModal from "../record/components/AddVIPModal";
import MergeToModal from "../record/components/MergeToModal";

export default {
  components: {
    AddGuestModal,
    AddStaffModal,
    AddVIPModal,
    MergeToModal,
    Tooltip,
    Btn
  },
  data() {
    const validateDate = (rule, value, callback) => {
      if (!value || value.length != 2) {
        callback(new Error("日期格式错误"));
      } else {
        callback();
      }
    };
    return {
      guestData: [],
      totalGuest: 0,
      currentPage: 1,
      pageSize: Constant.PAGE_SIZE,
      tableLoading: true,
      guestColumn: [
        {
          title: "姓名",
          key: "user_name",
          align: "center",
          width: "10%"
        },
        {
          title: "头像",
          key: "user_avatar",
          align: "center",
          width: "10%",
          render: (h, { row, column, index }) => {
            //拼装url
            let imgSrc = fakeAvatar;
            let encode = row[column.key];
            if (encode) {
              imgSrc = encode;
            }
            return (
              <div>
                <img class="user-avatar" alt="头像" src={imgSrc} />
              </div>
            );
          }
        },
        {
          title: "用户类型",
          key: "user_type_disp",
          align: "center",
          width: "100"
        },
        {
          title: "入库时间",
          //ellipsis: true,
          align: "center",
          width: "110",
          key: "create_at"
          // render: (h, { row, column, index }) => {
          // let access_from = row.access_from || "";
          // let access_to = row.access_to || "";
          // if (access_from == "" || access_to == "") {
          //   return "";
          // }
          // let form = DateUtils.format(
          //   DateUtils.parse(access_from, "yyyyMMdd"),
          //   "yyyy年MM月dd日"
          // );
          // let to = DateUtils.format(
          //   DateUtils.parse(access_to, "yyyyMMdd"),
          //   "yyyy年MM月dd日"
          // );
          // return (
          //   <row>
          //     <div style={{ lineHeight: "25px" }}>{form}</div>
          //     <div style={{ lineHeight: "25px" }}>{to}</div>
          //   </row>
          // );
          // }
        },
        {
          title: "特征",
          key: "user_picReg",
          align: "center",
          render: (h, { row, column, index }) => {
            let encodes = row[column.key];
            return (
              <div>
                {_.map(encodes, encode => {
                  //拼装url
                  let imgSrc = fakeAvatar;
                  if (encode !== "") {
                    imgSrc = "data:image/jpg;base64," + encode;
                  }
                  return <img class="user-avatar" alt="特征" src={imgSrc} />;
                })}
              </div>
            );
          }
        },
        {
          title: "操作",
          width: "180",
          align: "center",
          render: (h, { row, column, index }) => {
            const user_id = row.user_id;
            const user_name = row.user_name;
            const user_type = "guest_" + row.user_type;
            return h("div", [
              h(
                "Dropdown",
                {
                  props: {
                    trigger: "click"
                  },
                  on: {
                    "on-click": value => {
                      console.log(value); //此处的value和下面DropdownMenu选项的name对应
                      this.handleOption(value, row);
                    }
                  }
                },
                [
                  h("Button", {}, [
                    h("span", "标记为 "), //span中的内容
                    h("Icon", {
                      props: {
                        type: "arrow-down-b"
                      }
                    })
                  ]),
                  h(
                    "DropdownMenu",
                    {
                      slot: "list"
                    },
                    [
                      h(
                        "DropdownItem",
                        {
                          props: {
                            name: "staff"
                          }
                        },
                        "新建员工"
                      ),
                      h(
                        "DropdownItem",
                        {
                          props: {
                            name: "vip"
                          }
                        },
                        "新建 VIP"
                      ),
                      h(
                        "DropdownItem",
                        {
                          props: {
                            name: "guest"
                          }
                        },
                        "新建访客"
                      ),
                      h(
                        "DropdownItem",
                        {
                          props: {
                            name: "merge"
                          }
                        },
                        "合并至已有人员"
                      )
                    ]
                  )
                ]
              )
            ]);
          }
        },
        {
          title: " ",
          align: "center",
          width: "80",
          render: (h, { row, column, index }) => {
            const user_id = row.user_id;
            const user_name = row.user_name;
            return (
              <div class="operation">
                <Tooltip content="删除" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconDelete})` }}
                    onClick={() => this.handleDelStranger(user_id, user_name)}
                  />
                </Tooltip>
              </div>
            );
          }
        }
      ]
    };
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    }
  },
  mounted() {},
  beforeDestroy() {},
  created() {
    this.loadStrangerData();
  },
  methods: {
    updated() {
      this.loadStrangerData();
    },
    handleOption(type, row) {
      if (type == "staff") {
        this.$refs["addStaffModal"].showModal(row);
      } else if (type == "vip") {
        this.$refs["addVIPModal"].showModal(row);
      } else if (type == "guest") {
        this.$refs["addGuestModal"].showModal(row);
      } else if (type == "merge") {
        this.$refs["mergeToModal"].showModal(row);
      }
    },
    searchGuest() {
      // 检验关键词
      this.currentPage = 1;
      this.tableLoading = true;
      this.loadStrangerData();
    },
    loadStrangerData() {
      getStrangerData(this.currentPage, this.pageSize, this.queryWord)
        .then(json => {
          let { total, data } = transGuestData(json);
          this.totalGuest = total;
          this.guestData = data;
          this.tableLoading = false;
          return _.map(data, item => item.user_id);
        })
        .then(user_ids => this.asyncAvatar(user_ids));
    },
    translateDate(data) {
      let access_from = this.guestInfo[data].validate_date[0];
      let access_to = this.guestInfo[data].validate_date[1];
      if (access_from)
        this.guestInfo[data].access_from = DateUtils.format(
          access_from,
          "yyyyMMdd"
        );
      if (access_to)
        this.guestInfo[data].access_to = DateUtils.format(
          access_to,
          "yyyyMMdd"
        );
    },
    handleDelStranger(uid, name) {
      this.$Modal.confirm({
        title: "确认",
        content: "移除【" + name + "】？",
        onOk: () => {
          // 删除基本信息
          deleteUser({ user_id: [uid] }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.getStranger();
            }
          });
        }
      });
    },
    getStranger(page) {
      //获取分页参数，请求后端数据
      //console.log(page);
      //检验页码上下限
      this.currentPage = page;
      this.tableLoading = true;
      this.loadStrangerData();
    },
    asyncAvatar(user_ids) {
      _.forEach(user_ids, (user_id, index) => {
        getAvatar(user_id).then(json => {
          if (this.guestData[index] === undefined) {
            console.log(
              "存在数据加载错误，可能在异步过程完成前修改了原始的表数据"
            );
          }
          let result = transAvatar(json);
          //                        this.guestData[index].user_avatar = result.user_avatar;
          this.guestData[index].user_picReg = result.user_feature;
        });
        return true;
      });
    }
  }
};

function transGuestData(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { total: 0, result: {} };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined) {
    return { total: 0, result: {} };
  }
  let { total, result } = data;

  //to-do:检查data成员
  return {
    total,
    data: _.map(result, v => ({
      user_id: v["user_id"],
      user_name: v["user_name"],
      user_type: v["user_type"],
      user_type_disp: v["user_type_disp"],
      user_avatar: v["user_avatar"], //to-do:缺占位图base64
      user_picReg: [],
      user_sex: v["user_sex"] === 0 ? "0" : "1",
      user_phone: v["user_phone"],
      access_from: v["access_from"] || "",
      access_to: v["access_to"] || "",
      user_mark: v["user_mark"] || "",
      user_mark2: v["user_mark2"] || "",
      user_company: v["user_company"] || "",
      user_receptionist: v["user_receptionist"] || "",
      create_at: v["create_at"]
    }))
  };
}

function transAvatar(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { user_avatar: "", user_feature: ["", "", ""] };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined || data.length === 0) {
    return { user_avatar: "", user_feature: ["", "", ""] };
  }
  //提取->检验->组装
  return data[0];
}
</script>
